package com.ant.search.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @PostMapping("/test")
    public Map<String, Object> testSearch(@RequestBody JSONObject json){
        SearchRequest searchRequest = buildSearchRequest();
        try{
            //查询
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            log.info(response.toString());
        }catch (IOException ex){
            ex.printStackTrace();
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", "success");
        return resultMap;
    }

    private SearchRequest buildSearchRequest(){
        //构建查询语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //开始构建
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.matchAllQuery());
        sourceBuilder.query(boolQuery);
        //TODO 根据业务需求，构建更复杂的查询语句并封装
        //组装查询语句
        SearchRequest searchRequest = new SearchRequest(new String[]{""}, sourceBuilder);
        return searchRequest;
    }
}
